package com.lw.leetcode.str.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 722. 删除注释
 *
 * @author liw
 * @version 1.0
 * @date 2022/6/2 10:33
 */
public class RemoveComments {

    public List<String> removeComments(String[] source) {
        StringBuilder total = new StringBuilder(String.join("\n", source));
        int indexline = -1;
        int indexbb = -1;
        int i = 0;
        int length = total.length();
        while (i < length - 1) {
            char fi = total.charAt(i);
            char se = total.charAt(i + 1);
            if (fi == '/' && se == '/') {
                indexline = i;
                while (i < length && total.charAt(i) != '\n') {
                    i++;
                }
                total.delete(indexline, i);
                length -= (i - indexline);
                i = indexline - 1;
            } else if (fi == '/' && se == '*') {
                indexbb = i;
                i += 2;
                while (i < length - 1 && !(total.charAt(i) == '*' && total.charAt(i + 1) == '/')) {
                    i++;
                }
                total.delete(indexbb, i + 2);
                length -= (i + 2 - indexbb);
                i = indexbb - 1;
            }
            i++;
        }
        String[] resArray = total.toString().split("\n");
        List<String> res = new ArrayList<>(resArray.length);
        for (String str : resArray) {
            if (!"".equals(str)) {
                res.add(str);
            }
        }
        return res;
    }

}
